package com.ocm.controller.validator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.ocm.core.dto.StorageDto;
import com.ocm.core.service.StorageService;

@Component("storageValidator")
public class StorageValidator implements Validator {

   private StorageService storageService;

   @Autowired
   public StorageValidator(@Qualifier("storageService") StorageService storageService) {
      this.storageService = storageService;
   }

   public boolean supports(Class<?> classDef) {
      return StorageDto.class.isAssignableFrom(classDef);
   }

   public void validate(Object object, Errors errors) {
      validateClassDef(object, errors);
   }

   public void validateClassDef(Object object, Errors errors) {
      StorageDto storageDto = (StorageDto) object;
      ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "err.required");
      ValidationUtils.rejectIfEmptyOrWhitespace(errors, "displayName", "err.required");
      ValidationUtils.rejectIfEmptyOrWhitespace(errors, "storageURL", "err.required");
      if (!errors.hasFieldErrors("name")) {
         if (StringUtils.containsWhitespace(storageDto.getName())) {
            errors.rejectValue("name", "err.containsWhitespace");
         }
      }

      if (!errors.hasFieldErrors("name") && (storageDto.getId() == null || storageDto.getId() == 0)) {
         boolean existedName = storageService.hasExistName(storageDto.getName());
         if (existedName)
            errors.rejectValue("name", "err.unique");
      }
   }
}
